package org.budo.event.multicaster.aliyun.mns;

import java.util.List;

import org.budo.event.BudoEvent;
import org.budo.event.BudoEventListener;
import org.budo.event.DelayEvent;
import org.springframework.context.event.ContextRefreshedEvent;

import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.model.Message;

/**
 * @author lmw
 */
public class AliyunMnsEventMulticaster extends AbstractAliyunMnsEventMulticaster {
    private MNSClient mnsClient;

    public MNSClient getMnsClient() {
        return mnsClient;
    }

    public void setMnsClient(MNSClient mnsClient) {
        this.mnsClient = mnsClient;
    }

    public void multicastEvent(BudoEvent event) {
        CloudQueue cloudQueue = this.getCloudQueue();

        Message message = new Message();
        message.setMessageBody("序列化服务");
        if (event instanceof DelayEvent) {
            message.setDelaySeconds(((DelayEvent) event).getDelaySeconds());
        }

        cloudQueue.putMessage(message); // 可以异步put
    }

    private void popMessage() {
        CloudQueue cloudQueue = this.getCloudQueue();
        Message message = cloudQueue.popMessage();
        message.getMessageBody();
        BudoEvent event = null; // 反序列化

        List<BudoEventListener> eventListeners = this.retrieveEventListeners(event);

        for (BudoEventListener eventListener : eventListeners) {
            eventListener.onEvent(event);
        }
    }

    /**
     * 启动轮刷pop线程
     */
    public void onApplicationEvent(ContextRefreshedEvent event) {
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    AliyunMnsEventMulticaster.this.popMessage();
                }
            }
        }).start();
    }
}